//
//  JXProdComtController.m
//  JiaoX
//
//  Created by yinqy on 15/1/14.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.

//回复地址
#define REPLY_URL @"product/recomment"

#import "JXProdComtController.h"
#import "JXReplyCommentView.h"
#import "CommentCell.h"
#import "CommentUtils.h"
#import "HomeDataTool.h"
#import "ProdComtList.h"
#import "MJRefresh.h"

@interface JXProdComtController ()<UITableViewDelegate,UITableViewDataSource,JXReplyCommentViewDelegate,CommentCellViewDelegate>
{
    UITableView *_tableView;
    JXReplyCommentView *_replyView;
    NSMutableArray *_commentFrameArray;
    
    //回复需要用到的东西
    NSString *_commentId;
    NSString *_userIdOther;
    NSString *_userNameOther;
    NSString *_commentType;//回复的类型：0代表回复的是帖子，1代表回复的是主评论，2代表回复的是子评论
    
    //回复主评论的位置
    NSInteger _replySection;
    //回复子评论的位置
    NSInteger _replyIndex;

}
@property (nonatomic,copy)NSString *productId;

@end

@implementation JXProdComtController

+(instancetype)initWithProductId:(NSString *)productId;{
    JXProdComtController *result = [[JXProdComtController alloc]init];
    result.productId = productId;
    return result;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _replySection = _replyIndex = -1;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"聊聊这货";
    
    _commentFrameArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    [_tableView setHeight:_tableView.height-49];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorColor:JXColor(242, 242, 242)];
    [_tableView setTableFooterView:[[UIView alloc]init]];
    [self.view addSubview:_tableView];
    
    _replyView = [[JXReplyCommentView alloc]initWithPlaceholder:@"闲话这货"];
    _replyView.x = 0;
    _replyView.y = self.view.height-49;
    _replyView.delegate = self;
    [self.view addSubview:_replyView];
    
    [_tableView addHeaderWithTarget:self action:@selector(headerRefresh)];
    [_tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    
    [_tableView headerBeginRefreshing];
}

-(void)headerRefresh{
    [self requestDataWithId:self.productId lastComtId:@""];
}

-(void)footerRefresh{
    CommentViewFrame *frame = [_commentFrameArray lastObject];
    [self requestDataWithId:self.productId lastComtId:frame.comtInfo.commentId];
}

-(void)requestDataWithId:(NSString *)prodId lastComtId:(NSString *)lastComtId{
    [HomeDataTool getProdComtListWithProdId:prodId lastComtId:lastComtId success:^(ProdComtList *result) {
        if(!result.code){
            [self comtFramesWithData:result lastComtId:lastComtId];
        }else{
            //加载失败
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
        [self refreshComplete];
    } failure:^(NSError *error) {
        //加载失败
        [self refreshComplete];
    }];
}

-(void)refreshComplete{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
}


-(void)comtFramesWithData:(ProdComtList *)result lastComtId:(NSString *)lastComtId{
    if([Utils isBlankString:lastComtId]){
        [_commentFrameArray removeAllObjects];
    }
    for (int i=0; i<result.allComment.count; i++) {
        CommentViewFrame *frame = [[CommentViewFrame alloc]init];
        CommentInfo *comtInfo = result.allComment[i];
        //传递专题数据，计算所有子控件的frame
        frame.comtInfo = comtInfo;
        [_commentFrameArray addObject:frame];
    }
    [_tableView reloadData];
}

-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
    
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
}
#pragma Mark - 论坛评论相关 delegte

-(void)bottomViewReplyBtnClick:(NSString *)replyContent{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [CommentUtils replyCommentWithController:self replyUrl:REPLY_URL ReplyType:REPLY_TYPE_PRODID replyMainId:_productId commentId:_commentId replyContent:replyContent userIdOther:_userIdOther commentType:_commentType success:^(CommentInfo *result) {
        //这儿做了两件事，把键盘关掉，隐藏hud
        [self.view endEditing:YES];
        
        //在这儿处理回复成功相关逻辑
        JXLog(@"%lu",(unsigned long)_commentFrameArray.count);
        [CommentUtils replyResultHandle:_commentFrameArray replyType:REPLY_TYPE_PRODID commentType:_commentType currentComtId:result.commentId userIdOther:_userIdOther userNameOther:_userNameOther replyContent:replyContent section:_replySection orderBy:ASC doSomeBefore:^{
        } doSomeAfter:^{
            JXLog(@"%lu",(unsigned long)_commentFrameArray.count);
            [_tableView reloadData];
        }];
        
        //处理完逻辑之后重置相关参数，重置完毕之后再将hud关掉，并弹出回复成功tip
        [self reSetReplyParams];[HUD hide:YES];[DialogUtils showTipsWithView:self.navigationController.view String:@"回复成功"];
        
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"回复失败"];
    }];
}



/**
 *  CELL里面的回复按钮点击
 *
 *  @param index 点击的是第index条的主评论的回复
 */

-(void)replyBtnClick:(UIButton *)btn{
    _replySection = btn.tag;
    //回复的是主评论
    _commentType = @"1";
    
    CommentViewFrame *frame = _commentFrameArray[btn.tag];
    _commentId = frame.comtInfo.commentId;
    
    [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",frame.comtInfo.commentName]];
    
    [_replyView becomeFirstResponder];
}

/**
 *  CELL里面的私信按钮点击
 *
 *  @param btn
 */
- (void)chatBtnClick:(UIButton *)btn{
    JXLog(@"私信tag=%ld",(long)btn.tag);
}

/**
 *  CELL里面子评论被点击
 *
 *  @param section 点击的第section条主评论
 *  @param index   点击的是第index条子评论
 */
-(void)childReplyItemClick:(NSInteger)section index:(NSInteger)index{
    _replySection = section;_replyIndex = index;
    //回复的是子评论
    _commentType = @"2";
    
    CommentViewFrame *frame = _commentFrameArray[section];
    _commentId = frame.comtInfo.commentId;
    
    CommentInfo *reComt = frame.comtInfo.reComment[index];
    _userIdOther = reComt.commentUserId;
    _userNameOther = reComt.commentName;
    
    [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",reComt.commentName]];
    
    [_replyView becomeFirstResponder];
}

/**
 *  重置相关回复参数
 */
- (void)reSetReplyParams{
    _commentId = nil;
    _userIdOther = nil;
    _commentType = nil;
    _userNameOther = nil;
    [_replyView setPlaceHolder:nil];
    [_replyView setText:nil];
    _replySection = _replyIndex = -1;
    _commentType = @"0";
}

#pragma Mark - tableview 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_commentFrameArray.count){
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else{
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _commentFrameArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentCell *cell = [CommentCell cellWithTableView:tableView];
    [cell.comtCellView setTag:indexPath.row];
    [cell.comtCellView setDelegate:self];
    [cell setComtframe:_commentFrameArray[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentViewFrame *frame = _commentFrameArray[indexPath.row];
    return frame.frame.size.height;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self reSetReplyParams];
    [self.view endEditing:YES];
}

@end
